package com.study.aoki.reactive.endpoint

import com.study.aoki.reactive.bean.model.User
import com.study.aoki.reactive.repository.UserRepository
import com.study.aoki.reactive.service.UserService
import org.springframework.web.bind.annotation.*
import org.springframework.web.filter.reactive.ServerWebExchangeContextFilter
import org.springframework.web.server.ServerWebExchange
import reactor.core.publisher.Mono

/**
 * @author jiahan.zhou
 * @date 2020/11/24
 */
@RestController
@RequestMapping("/user")
class UserEndpoint(val userRepository: UserRepository,
                   val userService: UserService) {

    @GetMapping("/profile")
    fun profile(): Mono<User> {
        return Mono.subscriberContext()
                .map {
                    ServerWebExchangeContextFilter.get(it).orElse(null)
                }
                .map {
                    it.attributes["USER"] as User
                }
    }

    @PostMapping("create")
    fun create(@RequestParam("phone") phone: String): Mono<User> {
        val s = User(null, "A", phone)
        return userService.save(s)
    }
}